package top.wshape1.rpc.consumer.handler;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;
import top.wshape1.rpc.common.constant.ChannelConstant;
import top.wshape1.rpc.protocol.ProtocolFrameDecoder;
import top.wshape1.rpc.protocol.RpcMessageCodec;

import java.util.concurrent.TimeUnit;

/**
 * @author Wshape1
 * @version 1.0
 * @description 消费者的Channel初始化器
 * @since 2024-02-02
 */

@ChannelHandler.Sharable
public class ConsumerChannelInitializer extends ChannelInitializer<SocketChannel> {
    private static LoggingHandler LOGGING_HANDLER;
    private static RpcMessageCodec RPC_MESSAGE_CODEC;
    private static RpcResponseHandler RPC_RESPONSE_HANDLER;

    private void initHandler() {
        LOGGING_HANDLER = new LoggingHandler("ConsumerLoggingHandler", LogLevel.DEBUG);
        RPC_MESSAGE_CODEC = new RpcMessageCodec();
        RPC_RESPONSE_HANDLER = new RpcResponseHandler();
    }

    @Override
    protected void initChannel(SocketChannel socketChannel) {
        if (RPC_MESSAGE_CODEC == null) {
            initHandler();
        }

        // 空闲中断处理器
        socketChannel.pipeline().addLast(new IdleStateHandler(0, ChannelConstant.IDLE_WRITER_TIME, 0, TimeUnit.MILLISECONDS));
        // 协议解码器
        socketChannel.pipeline().addLast(new ProtocolFrameDecoder());
        // 日志处理器
        socketChannel.pipeline().addLast(LOGGING_HANDLER);
        // 消息编解码器
        socketChannel.pipeline().addLast(RPC_MESSAGE_CODEC);
        // 消费者空闲中断消息处理器
        socketChannel.pipeline().addLast(new ConsumerIdleHandler());
        // Rpc响应处理器
        socketChannel.pipeline().addLast(RPC_RESPONSE_HANDLER);
    }
}
